using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;

namespace Tron.Animations
{
    [Serializable]
    public abstract class Animator : GameComponent
    {
        Queue<Animation> animationQueue = new Queue<Animation>();
        Animation currentAnimation;

        public bool Idle
        {
            get
            {
                return animationQueue.Count == 0 && currentAnimation == null;
            }
        }

        public bool NearlyIdle(float maximumTimeLeft)
        {
            return Idle || (animationQueue.Count == 0 && currentAnimation.TimeLeft <= maximumTimeLeft);
        }

        public int QueueCount
        {
            get
            {
                return animationQueue.Count;
            }
        }

        protected Animator(Game game)
            : base(game) { }

        protected void Enqueue(Animation animation)
        {
            animationQueue.Enqueue(animation);
        }

        public void Clear()
        {
            animationQueue.Clear();
            currentAnimation = null;
        }

        public override void Update(GameTime gameTime)
        {
            bool changedAnimation;
            do
            {
                changedAnimation = false;
                if (currentAnimation != null)
                    currentAnimation.Update(gameTime);
                if (currentAnimation == null || currentAnimation.Finished)
                {
                    if (currentAnimation != null)
                        currentAnimation.Finish();
                    if (animationQueue.Count > 0)
                    {
                        double overflow = 0;
                        if (currentAnimation != null)
                            overflow = currentAnimation.Overflow;
                        currentAnimation = animationQueue.Dequeue();

                        currentAnimation.GiveOverflow(overflow);
                        currentAnimation.Initialize(gameTime);

                        changedAnimation = true;
                    }
                    else
                        currentAnimation = null;
                }
            } while (changedAnimation);
        }
    }
}
